<template>
  <div class="" style="position: relative">
    <div ref="mapDiv" class="full-height full-width" />
    <div
      class="absolute full-width"
      :style="$q.screen.lt.md ? 'top: 15px;' : 'top: 0;'"
      :class="ui.modelClass"
    >
      <div class="absolute-center text-bold">{{ map.name }}</div>
      <div v-if="!$q.screen.lt.md">
        <q-toggle
          class="float-right q-mr-sm"
          :label="$t(lang + '视角锁定')"
          v-model="viewLocking"
          v-if="props.robotShow"
        />
        <q-toggle
          class="float-right q-mr-sm"
          :label="$t(lang + '点位名称')"
          v-model="pointNameShow"
          v-if="props.pointShow"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, onUnmounted, watch, computed } from "vue";
import PixiMap from "src/utils/PixiMap";
import { api } from "boot/axios";
import { useAPIStore } from "stores/api";
import { useUiStore } from "stores/ui";
import RosClient from "src/utils/rosClient";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";

const t = useI18n().t; // 语言包
const lang = "devicePage.deviceMap.";
const $q = useQuasar();
const props = defineProps({
  // 地图Id
  mapId: { type: String, default: "" },
  // 是否连接到了中控
  centerConnected: { type: Boolean, default: true },
  // 是否显示点位
  pointShow: { type: Boolean, default: false },
  // 是否显示机器人
  robotShow: { type: Boolean, default: false },
});
const emit = defineEmits(["getPoint"]);
const ui = useUiStore();
const pixiMap = PixiMap();
const rosClient = RosClient();
const mapDiv = ref(); //  地图dom
const pointSourceList = ref([]); //  点位数据列表
const viewLocking = ref(false); // 是否视角锁定
const pointNameShow = ref(true); // 是否显示点位名称
const map = ref({}); // 地图实体
const mapId = computed(() => props.mapId);

// 判断是否连接到中控，如未连接到访问机器人本身地图
// const mapUrl = computed(() => props.centerConnected ? useAPIStore().mapUrl : useAPIStore().amrUrl)
const mapPoseUrl = computed(() =>
  props.centerConnected ? useAPIStore().mapUrl : useAPIStore().amrUrl
);

onMounted(() => {
  // 判断是否需要显示机器人
  if (props.robotShow) rosClient.createWs();
  initPixi();
  pixiMap.clickPoint = getPoint;
});

onUnmounted(() => {
  // 判断是否需要显示机器人
  if (props.robotShow) rosClient.closeWs();
  pixiMap.destroyStage();
});
watch(mapId, (value) => {
  if (!value) return;
  initPixi();
});

// 是否视角锁定
watch(viewLocking, (value) => {
  // 锁定后自动对焦机器人
  if (value) {
    $q.dialog({
      title: t(lang + "是否锁定视角"),
      message: t(lang + "锁定后将无法拖动地图"),
      ok: t("ok"),
      cancel: t("cancel"),
      persistent: true,
    })
      .onOk(() => {
        pixiMap.focus();
        pixiMap.viewLocking = value;
      })
      .onCancel(() => {
        // 取消恢复以前状态
        viewLocking.value = !value;
      });
  } else {
    pixiMap.viewLocking = value;
  }
});

// 是否显示点位名称
watch(pointNameShow, (value) => {
  pixiMap.showPointName(value);
});

// 监听激光雷达进行更新
watch(rosClient.scanPose, (value) => {
  pixiMap.drawScan(value);
});

// 监听设备位置
watch(rosClient.robotPose, (value) => {
  pixiMap.updateRobot(value);
});

// ------地图渲染----------------------------------------------------------------------
// 创建画布
function initPixi() {
  mapDiv.value.innerHTML = "";
  pixiMap.div = mapDiv.value;
  pixiMap.stage = pixiMap.createStage(mapDiv.value);
  initImg();
  if (props.robotShow) loadRobot();
}

// 初始化素材
function initImg() {
  const poseImg = new Image();
  poseImg.src = "map/pose.png";
  window.URL.revokeObjectURL(poseImg.src);
  poseImg.onload = () => {
    loadMap();
    pixiMap.setPointStyle({ img: poseImg });
  };
}

// 加载地图
function loadMap() {
  if (!mapId.value) return;
  // 根据地图id获取地图信息
  api.get(useAPIStore().amrUrl + "map/id/" + mapId.value).then((res) => {
    map.value = res.data;
    console.log("----------地图", res);
    const mapImage = new Image();
    mapImage.src =
      "data:image/" +
      (res.data.format === "landmark" ? "png" : res.data.format) +
      ";base64," +
      res.data.mapBase64;
    window.URL.revokeObjectURL(mapImage.src);
    // 地图图片加载成功
    mapImage.onload = () => {
      // 渲染地图
      pixiMap.map = pixiMap.createMap({
        resolution: res.data.resolution,
        x: res.data.x,
        y: res.data.y,
        img: mapImage,
      });
      // 加载点位
      // 判断是否需要显示
      if (props.pointShow) loadRoutes();
      loadPolygons();
      pixiMap.updateStage();
    };
  });
}

// 加载机器人
function loadRobot() {
  const robotImg = new Image();
  robotImg.src = "map/arrow.png";
  window.URL.revokeObjectURL(robotImg.src);
  // 机器人图片加载成功
  robotImg.onload = () => {
    // 渲染机器人
    pixiMap.robot = pixiMap.createRobot({ img: robotImg });
    // 更新机器人位置
    rosClient.subscribe("/robot_pose");
    // 订阅激光雷达数据
    rosClient.subscribe("/scan_simplified");
    pixiMap.updateStage();
    // 加载完毕后，视角落到机器人上
    setTimeout(() => {
      pixiMap.focus();
    }, 500);
  };
}

// 加载点位
function loadRoutes() {
  // 根据地图id获取点位信息
  api.get(mapPoseUrl.value + "mapPose/ros/mapID/" + mapId.value).then((res) => {
    pointSourceList.value = res.data;
    // 点位名常显
    pixiMap.pointNameShow = true;
    // 绘制点位路线
    pixiMap.drawRail(pointSourceList.value);
  });
}

// 加载安全区
function loadPolygons() {
  api
    .get(useAPIStore().mapUrl + "new/polygon/mapID/" + mapId.value)
    .then((res) => {
      if (res.data.code === 200) {
        pixiMap.drawPolygon(res.data.data);
      }
    });
}

// 点击获取点位信息
function getPoint(p) {
  pixiMap.highlight(p.id);
  emit("getPoint", p);
}
</script>

<style scoped></style>
